<?php

namespace app\admin\controller\system;

use app\common\controller\AdminBase;
use app\common\controller\PCBase;
use think\App;
use think\facade\Db;
use think\facade\Log;
use util\Token;

/**
 * menu控制器
 */
class Menu extends PCBase
{

    protected $model = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\SystemMenu();
    }







    /**
     * 添加
     */
    public function add()
    {
        $post = $this->request->post();
        try {
            if ($post['type'] == 1) {
                if ($post['pid'] == 0) {
                    $post['component'] = "Layout";
                } else {
                    $post['component'] = "ParentView";
                }
            }
            //path 如果不是外链 判断是否唯一
            $path = isset($post['path']) ? $post['path'] : "";
            if ($path && stripos($path, 'http') === false) {
                $count = $this->model->where('path', $path)->count();
                if ($count > 0) {
                    return $this->jsonMessage(201, false, '路由地址已存在,换个试试', null);
                }
            }
            $result = $this->model->save($post);
            if (!$result) {
                return $this->jsonMessage(201, false, '添加失败', null);
            }
            return $this->jsonMessage(200, true, '添加成功', null);
        } catch (\Exception $e) {
            return $this->jsonMessage(201, false, $e->getMessage(), null);
        }
    }

    /**
     * 修改
     *
     */
    public function edit($id)
    {
        $id = input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return $this->jsonMessage(201, false, '数据不存在', null);
        }

        $post = $this->request->post();
        if ($post['type'] == 1) {
            if ($post['pid'] == 0) {
                $post['component'] = "Layout";
            } else {
                $post['component'] = "ParentView";
            }
        }
        try {
            //path 如果不是外链 判断是否唯一
            $path = isset($post['path']) ? $post['path'] : "";
            if ($path && stripos($path, 'http') === false) {
                $count = $this->model->where('path', $path)->where('id', '<>', $post['id'])->count();
                if ($count > 0) {
                    return $this->jsonMessage(201, false, '路由地址已存在,换个试试', null);
                }
            }
            $result = $row->save($post);
            if ($result) {
                return $this->jsonMessage(200, true, '添加成功', null);
            }
            return $this->jsonMessage(201, false, '保存失败', null);
        } catch (\Exception $e) {
            Log::error("--------:" . $e);
            return $this->jsonMessage(201, false, '保存失败', null);
        }
        return $this->jsonMessage(200, true, 'ok', null);
    }

    /**
     * 获取所有菜单(无层级)
     */

    public function index()
    {
        $status = $this->request->request('status');
        $limit  = $this->request->request('limit') ?? 1000;
        $menu_type = $this->request->request('menu_type'); //1：目录 2：菜单 3：按钮权限  4：目录+菜单 不传取所有
        $where = [];
        if ($status) {
            $where['status'] = $status;
        }
        if ($menu_type) {
            if ($menu_type == 4) {
                $where[] = ['type', '<', 3];
            }
            if ($menu_type < 4) {
                $where['type'] = $menu_type;
            }
        }
        $list  = $this->model
                  ->where($where)
                  ->order('weigh desc,id asc')
                  ->paginate($limit);
        $data = [
            'total' => $list->total(),
            'list'  => $list->items(),
        ];
        return $this->jsonMessage(200, true, '获取成功!', $data);
    }

    /**
     * 获取所有菜单(无层级)
     */

    public function adminIndex()
    {
        $params    = $this->request->post();
        $limit     = $params['limit']??1000;
        $status    = $params['status']??'';
        $menu_type = $this->request->post('menu_type'); //1：目录 2：菜单 3：按钮权限  4：目录+菜单 不传取所有
        $where = [];
        if ($status) {
            $where['status'] = $status;
        }
        if ($menu_type) {
            if ($menu_type == 4) {
                $where[] = ['type', '<', 3];
            }
            if ($menu_type < 4) {
                $where['type'] = $menu_type;
            }
        }

        /**
         * 管理员对于菜单
         */
        $adminId = $this->getAdminId();
        $admin_groups = Db::name("system_group_admin")
            ->where('admin_id', $adminId)
            ->column('group_id');
        $group_menu = Db::name('system_group_menu')
            ->where('group_id', 'in', $admin_groups)
            ->column('menu_id');
        if (!in_array("1", $admin_groups)) {
            $where[] = ['id', 'in', $group_menu];
        }


        $list = $this->model->where($where)->order('weigh desc,id asc')->paginate($limit);
        $data = [
            'total' => $list->total(),
            'list'  => $list->items(),
        ];
        return $this->jsonMessage(200, true, '获取成功!', $data);
    }
    /**
     * 数据删除
     */
    public function delete($id)
    {

        $id = input('id');
        $row = $this->model->find($id);
        if ($row->isEmpty()) {
            return $this->jsonMessage(200, true, '数据不存在', null);

        }
        $count = $this->model->where('pid', $id)->count();
        if ($count > 0) {
            return $this->jsonMessage(200, true, '请先删除子菜单/字权限', null);
        }
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            return $this->jsonMessage(200, true, '删除失败', null);
        }
        if($save){
            return $this->jsonMessage(200, true, '删除成功!', null);
        }else{
            return $this->jsonMessage(201, false, '删除失败', null);
        }
    }

    /**
     * 查找
     */
    public function find($id)
    {
        $id = input('id');
        $row = $this->model->find($id);
        unset($row['create_time']);
        unset($row['update_time']);
        if (empty($row)) {
            return $this->jsonMessage(200, true, '数据不存在', null);
        }
        return $this->jsonMessage(200, true, '获取成功!', $row);
    }


    /**
     * 状态启用、禁用
     */
    public function status($id, $status, $type)
    {
        $row = $this->model->find($id);
        if (empty($row)) {
            return $this->jsonMessage(201, false, '数据不存在!', null);
        }
        $msg = $status == 0 ? "禁用" : "启用";
        try {
            switch ($type) {
                case '1':
                    $row->status = $status;
                    break;
                case '2':
                    $row->activeFlag = $status;
                    break;
                default:
                    $row->status = $status;
            }
            
            $row->save();
            return $this->jsonMessage(200, true, '操作成功!', null);
        } catch (\Exception $e) {
            return $this->jsonMessage(201, false, '操作失败!', null);
        }
    }
}
